package code_analysis

import (
	"strings"
)

// 判断字符串是否符合变量命名规则 字母数字下划线组成,开头不能是数字
func IsVariableNameRule(str string) bool {
	//判断是否全是字母数字下划线
	for _, v := range str {
		if v < 'a' || v > 'z' {
			if v < 'A' || v > 'Z' {
				if v < '0' || v > '9' {
					if v != '_' {
						return false
					}
				}
			}
		}
	}
	//判断开头不能是数字
	if str[0] >= '0' && str[0] <= '9' {
		return false
	}
	return true
}

// 判断是否是函数调用 show("123",123)
func GetFunNameAnrParam(codeLine string) (string, []string) {
	funName := IsFunCall(codeLine)
	if funName == "" {
		return "", []string{}
	}
	//取出函数参数
	funParam := codeLine[len(funName)+1 : strings.LastIndex(codeLine, ")")]
	if funParam == "" {
		return funName, []string{}
	}
	maps, both := FuncPickBoth(funParam)
	split := strings.Split(both, ",")
	for i, v := range split {
		split[i] = RestorePickBoth(v, maps)
	}
	return funName, split
}

// 判断是否是函数调用 show("123",123)
func IsFunCall(codeLine string) string {
	//判断是否存在(
	//获取第一个(的位置
	index := strings.Index(codeLine, "(")
	if index == -1 {
		return ""
	}
	//判断(和)是否成对出现
	count := strings.Count(codeLine, "(")
	if count > 0 && count != strings.Count(codeLine, ")") {
		return ""
	}
	//截取到(之前的字符串
	funName := codeLine[:index]
	rule := IsVariableNameRule(funName)
	if !rule {
		return ""
	}
	return funName
}
